#!/bin/bash

# OpenHarmony Knowledge Service 启动脚本

set -e

echo "========================================="
echo "  OpenHarmony Knowledge Service"
echo "========================================="

# 检查Java环境
if ! command -v java &> /dev/null; then
    echo "❌ 错误: 未找到Java运行环境"
    echo "请安装Java 17或更高版本"
    exit 1
fi

JAVA_VERSION=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}' | cut -d'.' -f1)
if [ "$JAVA_VERSION" -lt 17 ]; then
    echo "❌ 错误: Java版本过低 (当前: $JAVA_VERSION, 需要: 17+)"
    exit 1
fi

echo "✅ Java版本: $JAVA_VERSION"

# 设置环境变量
export OH_CODE_PATH="${OH_CODE_PATH:-./../ohcode}"
export GLM_API_KEY="${GLM_API_KEY:-df6af53dd93b4afe9c1f0781f198305a.zcW6GYuBCOz3Xb27}"

echo "📁 OHCode路径: $OH_CODE_PATH"

# 检查ohcode目录是否存在
if [ ! -d "$OH_CODE_PATH" ]; then
    echo "⚠️  警告: ohcode目录不存在: $OH_CODE_PATH"
    echo "知识库服务将无法扫描代码"
fi

# 创建数据目录
mkdir -p ./data/index
mkdir -p ./logs

# 检查是否已编译
if [ ! -f "target/openharmony-knowledge-service-1.0.0.jar" ]; then
    echo "📦 编译项目..."
    mvn clean package -DskipTests
fi

# 启动服务
echo "🚀 启动服务..."
java -Xms512m -Xmx2048m \
     -XX:+UseG1GC \
     -Dfile.encoding=UTF-8 \
     -jar target/openharmony-knowledge-service-1.0.0.jar \
     --spring.profiles.active=prod

echo "✅ 服务已启动"
echo "📊 访问: http://localhost:8087"
echo "📊 统计: http://localhost:8087/api/knowledge/stats"
echo "📊 健康检查: http://localhost:8087/actuator/health"

